package com.ruoci.redis.requestlimit.guava;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @Author yang
 **/
@Slf4j
@RestController
@RequestMapping("/limit")
public class LimitController {
    /**
     * 限流策略：1秒钟2个请求
     */
    private final RateLimiter limiter = RateLimiter.create(2,1,TimeUnit.MINUTES);

    private DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss");

    @GetMapping("/test1")
    public String testLimiter() {
        //500毫秒内，没拿到令牌，就直接进入服务降级
        boolean tryAcquire = limiter.tryAcquire(500, TimeUnit.MILLISECONDS);
        if (tryAcquire) {
            log.info("获取令牌成功，时间{}", LocalDateTime.now().format(dtf));
            return "请求成功";
        }else {
            throw new RuntimeException("request too much");
        }

    }



}
